package com.example.recall_application.mvp.presenter;

import android.app.Application;
import android.content.ContentProviderOperation;
import android.content.ContentResolver;
import android.content.Context;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.provider.CallLog;
import android.provider.ContactsContract;
import androidx.annotation.RequiresApi;
import android.text.TextUtils;
import android.widget.TextView;

import com.example.recall_application.R;
import com.example.recall_application.mvp.adapter.BaseAdapter;
import com.example.recall_application.mvp.entity.Config;
import com.example.recall_application.mvp.entity.ConfigRequest;
import com.example.recall_application.mvp.entity.EventBusPhonePRMN;
import com.example.recall_application.utils.CallLogHelper;
import com.example.recall_application.utils.ContactsUtils;
import com.example.recall_application.utils.PhoneUtil;
import com.example.recall_application.utils.SimHelper;
import com.example.recall_application.utils.SmsHelper;
import com.example.recall_application.utils.TimeUtils;
import com.jess.arms.integration.AppManager;
import com.jess.arms.di.scope.ActivityScope;
import com.jess.arms.mvp.BasePresenter;
import com.jess.arms.http.imageloader.ImageLoader;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import me.jessyan.rxerrorhandler.core.RxErrorHandler;

import javax.inject.Inject;

import com.example.recall_application.mvp.contract.ContacksContract;

import org.simple.eventbus.Subscriber;
import org.simple.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.example.recall_application.mvp.presenter.MainPresenter.uuid;


/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 11/18/2019 18:29
 * <a href="mailto:jess.yan.effort@gmail.com">Contact me</a>
 * <a href="https://github.com/JessYanCoding">Follow me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms">Star me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms/wiki">See me</a>
 * <a href="https://github.com/JessYanCoding/MVPArmsTemplate">模版请保持更新</a>
 * ================================================
 */
@ActivityScope
public class ContacksPresenter extends BasePresenter<ContacksContract.Model, ContacksContract.View> {
    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;
    public static ArrayList<String> mData = new ArrayList<>();
    private ArrayList<String> mData_real;

    private ArrayList<String> callLog = new ArrayList<>();
    BaseAdapter<String> adapter;
    ContentResolver resolver = null;
    Uri uri_contact;
    Uri uri_call;
    Uri uri_sms;
    Uri uri_sms_box;
    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(msg.what == 100002 && !mData.contains("通话记录:")){
                mData.add("通话记录:");
            }
            else if(msg.what == 100003 && !mData.contains("通讯录:")){
                mData.add("通讯录:");
            }
            else if(msg.what == 100001 && !mData.contains("短信:")){
                mData.add("短信:");
            }
            // callLog.addAll((Collection<? extends String>) msg.obj);
            callLog.clear();
            mData.addAll((Collection<? extends String>) msg.obj);
//                mData_real = new ArrayList<>(new HashSet<String>(mData));
//                mData.clear();
//                mData.addAll(mData_real);
            for (int i = 0; i < mData.size(); i++) {
                callLog.add(PhoneUtil.handlePhone(mData.get(i)));
            }
            mData.clear();
            mData.addAll(callLog);
            removeDuplicate(mData);
            adapter.notifyDataSetChanged();
        }
    };

    @Inject
    public ContacksPresenter(ContacksContract.Model model, ContacksContract.View rootView) {
        super(model, rootView);
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        this.mErrorHandler = null;
        this.mAppManager = null;
        this.mImageLoader = null;
        this.mApplication = null;
    }

    /**
     * 监听content变化
     */
    public void listenerContent(){
        observer observer = new observer(new Handler());
        resolver = mApplication.getContentResolver();
        uri_contact = ContactsContract.Contacts.CONTENT_URI;
        uri_call = CallLog.Calls.CONTENT_URI;
        uri_sms = Uri.parse("content://sms/");
        uri_sms_box = Uri.parse("content://mms-sms/conversations");
        resolver.registerContentObserver(uri_contact,true,observer);
        resolver.registerContentObserver(uri_call,true,observer);
        resolver.registerContentObserver(uri_sms,true,observer);
        resolver.registerContentObserver(uri_sms_box,true,observer);
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    public void getContacts() {
        mData.clear();
        adapter = new BaseAdapter<String>(mApplication,mData) {
            @Override
            public void convert(int position, BaseViewHolder holder, String myContacts) {

                ((TextView)holder.getView(R.id.text)).setText(myContacts);
            }

            @Override
            public int getLayoutId(int viewType) {
                return R.layout.item_contacts;
            }
        };


       // ContactsUtils.getContactId(mApplication,"15201962331");
       // ContactsUtils.deletLastCallLog("15201962331",mApplication);
      // ContactsUtils.insertCallLog("110110101",mApplication);

        mData.add("转呼号码：");
        mData.addAll(Arrays.asList(MainPresenter.config_p.getPRMN().split(",")));
        getSimContacts(null);
        getSmsContacts(1);
        getSmsContacts(2);
        String time = TimeUtils.getDateBefore(new Date(), Integer.parseInt(MainPresenter.config_p.getP2()));
        getCallLogsContacts("type = 2 and date > "+time);
        getCallLogsContacts("type = 1 and duration > "+ MainPresenter.config_p.getP1());
   //     mData.addAll(PhoneUtil.getPhone(mApplication));



//        mData.add("手机短信:");
//        String time = TimeUtils.getDateBefore(new Date(),100);
//        String time_1 = TimeUtils.getDateBefore(new Date(),3);
//        List<String> data_sms_1 = SmsUtil.getSmsFromPhone(mApplication,time,1);//发送类的短信
//        List<String> data_sms_2 = handleSMSContent(SmsUtil.getSmsFromPhone(mApplication,time_1,2));//通知类的短信
//        data_sms_1.addAll(data_sms_2);
//        mData.addAll(data_sms_1);
//
//        mData.add("通话记录:");
//        CallLogHelper callLogHelper = new CallLogHelper(mApplication,handler,"type = 2 and date > "+time);
//        CallLogHelper callLogHelper2 = new CallLogHelper(mApplication,handler,"type = 1 and duration > "+ 20);
//        callLogHelper.readData();
//        callLogHelper2.readData();
//        removeDuplicate(mData);
         mRootView.setAdapter(adapter);
    }

    @Subscriber(mode = ThreadMode.MAIN)

    public void callForwarding(EventBusPhonePRMN eventBusPhone){
        ConfigRequest configRequest = new ConfigRequest();
        configRequest.setUNIONID(uuid);
        //configRequest.setPhone(eventBusPhone.getPhone());
        mModel.callForwarding(configRequest)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Config>() {
                    @Override
                    public void accept(Config o) throws Exception {
                        ContactsUtils.deletLastCallLog(PhoneUtil.handlePhone(o.getMMN()),eventBusPhone.getPhone(),mApplication);
                    }
                });

    }


    public void changeCallLogs(String condition){
        ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
        ContentProviderOperation contentProviderOperation = ContentProviderOperation
                .newUpdate(ContactsContract.Data.CONTENT_URI)
                .withSelection(ContactsContract.CommonDataKinds.Phone.NUMBER+"=? ",new String[]{"18317722576"})
                .withValue(ContactsContract.CommonDataKinds.Phone.NUMBER,"1110110")
                .build();
        ops.add(contentProviderOperation);

        try {
            mApplication.getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    //根据联系人电话号码查询名字

    public static String queryNameFromContactsByNumber(Context context, String number) {

        String name = null;
        if (context != null && number != null && !"".equals(number.trim())) {
            Uri uri = Uri.withAppendedPath(
                    ContactsContract.CommonDataKinds.Phone.CONTENT_FILTER_URI,
                    number);
            Cursor nameCursor = context.getContentResolver().query(uri,

                    new String[] { "display_name" }, null, null, null);

            if (nameCursor != null) {

                if (nameCursor.getCount() > 0) {
                    nameCursor.moveToFirst();
                    name = nameCursor.getString(0);
                }
            }
        }
        return name;
    }



    /**
     * 获取通讯录
     */
    public void getSimContacts(String condition){
        SimHelper simHelper = new SimHelper(mApplication,handler,condition);
        simHelper.readData();
    }

    /**
     * 获取短信中符合条件的
     * @param type
     */
    public void getSmsContacts(int type){
        SmsHelper smsHelper = new SmsHelper(mApplication,handler,type);
        smsHelper.readData();
    }

    /**
     * 获取通话记录
     */
    public void getCallLogsContacts(String condition){
        CallLogHelper callLogHelper = new CallLogHelper(mApplication,handler,condition);
        callLogHelper.readData();
    }


    /**
     * 处理短信手机号
     */
    private List<String> handleSMSPhone(List<String> sms_data){
        List<String> handle_data = new ArrayList<>();
        for (String item:sms_data) {
            if(isNumeric(item)){
                handle_data.add(item);
            }
        }
        return handle_data;
    }

    /**
     * 处理短信中的内容
     * @param sms_data
     * @return
     */
    private List<String> handleSMSContent(List<String> sms_data){
        List<String> handle_data = new ArrayList<>();
        for (String item: sms_data) {
            if(item.contains("盒马")||item.contains("京东")){

                if(!TextUtils.isEmpty(checkCellphone(item))){
                    handle_data.add(checkCellphone(item));
                }
            }
        }
        return handle_data;
    }


    /**
     * 查询符合的手机号码
     * @param str
     */
    public  String checkCellphone(String str){
        // 将给定的正则表达式编译到模式中
        Pattern pattern = Pattern.compile("((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(18[0,5-9]))\\d{8}");
        // 创建匹配给定输入与此模式的匹配器。
        Matcher matcher = pattern.matcher(str);
        //查找字符串中是否有符合的子字符串
        while(matcher.find()){
           return matcher.group();
        }
        return "";
    }


    /**
     * 数字串 正则匹配
     * @param s
     * @return
     */
    public boolean isNumeric(String s) {
        if (s != null && !"".equals(s.trim()))
            return s.matches("^[0-9]*$");
        else
            return false;
    }

    /**
     * 监听内容提供者变化
     */
    class observer extends ContentObserver{

        public observer(Handler handler) {
            super(handler);
        }

        @RequiresApi(api = Build.VERSION_CODES.M)
        @Override
        public void onChange(boolean selfChange, Uri uri) {
            super.onChange(selfChange, uri);
                //Toast.makeText(mApplication, "发生变化！", Toast.LENGTH_SHORT).show();
                getContacts();
        }
    }

    public  List  removeDuplicate(List list){
        if(list!=null){
            try{
                for  ( int  i  =   0 ; i  <  list.size()  -   1 ; i ++ )  {
                    for  ( int  j  =  list.size()  -   1 ; j  >  i; j -- )  {
                        if  (list.get(j).equals(list.get(i)))  {
                            list.remove(j);
                        }
                    }
                }
            }catch (Exception e){
                e.toString();
            }
        }
        return list;
    }
}
